<!--
 * @Author: zhuxiaoyi
 * @Date: 2024-01-09 10:50:36
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2024-07-05 23:24:51
 * @Description: 
-->
<template>
  <el-row>
    <el-col :span="24" class="paltform-container" :style="`height:${view.height}px`">
      <div class="header">
        <div class="tit-warp">
          <span class="tit-name"> 无人机现场执法客户端软件</span>
        </div>
      </div>
    <!--   <div class="tab-container">
        <div class="tab-box left-box">
          <div class="custom-button-warp">
            <div class="custom-button active">土含与蒸散发反演</div>
          </div>
          <div class="custom-button-warp">
            <div class="custom-button">灌溉面积监测</div>
          </div>
          <div class="custom-button-warp">
            <div class="custom-button">灌溉水量监测</div>
          </div>
        </div>
        <div class="tab-box middle-box"></div>
        <div class="tab-box right-box">
          <div class="custom-button-warp">
            <div class="custom-button">多要素联合模拟</div>
          </div>
          <div class="custom-button-warp">
            <div class="custom-button">耗水过程解析</div>
          </div>
          <div class="custom-button-warp">
            <div class="custom-button">示范成果展示</div>
          </div>
        </div>
      </div> -->
      <div class="task-card" style="width: 400px">
        <div style="
            color: #fff;
            font-size: 16px;
            padding-bottom: 10px;
            cursor: pointer;
          ">
          <!-- 反演产品 -->
        </div>
        <el-form :label-position="'left'" label-width="70px" :model="formLabelAlign" class="filter-container">
          <el-row>
           <!--  <el-col :span="24">
              <el-form-item label="图层类型">
                <el-select v-model="satType" class="m-2" placeholder="请选择图层类型" size="small" style="width: 305px"
                  clearable @change="getPorducts">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="24">
              <el-form-item label="图层日期">
                <el-date-picker v-model="startTime" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期"
                  class="input-box" :size="'small'" style="width: 306px" @change="getPorducts" />
              </el-form-item>
            </el-col>
            <el-col :span="19">
              <el-form-item label="图层名称">
                <el-input v-model="imageName" clearable style="width: 305px" :size="'small'" placeholder="请输入图层名称"
                  @change="getPorducts" @keyup.enter="getPorducts"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-button type="primary" size="small" style="margin: 5px; width: calc(100% - 5px)"
                @click="getPorducts">查询</el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-row style="margin-top: 10px">
          <el-col :span="24">
            <el-table ref="tableRef" :data="tableData" style="width: 100%" size="small" :height="490"
              @current-change="viewRecordHandler" highlight-current-row v-loading="productLoading">
              <el-table-column type="expand">
                <template #default="props">
                  <ul class="detial-con">
                    <li>图层名称: &nbsp; {{ props.row.productName }}</li>
                    <li>图层日期: &nbsp; {{ utils.formatDate(props.row.produceDate) }}</li>
                    <li>图层类型: &nbsp; <el-tag type="primary" size="small">{{ props.row.satelliteType }}</el-tag></li>
                  </ul>
                </template>
              </el-table-column>
              <el-table-column :align="'center'" type="index" label="序号" width="50" />
              <el-table-column :align="'center'" prop="name" label="名称">
                <template #default="scope">
                  <div style="width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
                    :title="scope.row.productName">
                    {{ scope.row.productName }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column :align="'center'" width="105px" prop="produceDate" label="监测日期">
                <template #default="scope">
                  <div style="width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
                    :title=" utils.formatDate(scope.row.produceDate)">
                    {{ utils.formatDate(scope.row.produceDate) }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column :align="'center'" label="操作" width="50px">
                <template #default="scope">
                  <el-button link type="primary" size="small" disabled @click.stop="">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="24" style="padding:10px 5px 5px; overflow: auto" class="page-container">
            <pagination-custom :pagination="pagination" @handleSizeChange="productSizeChangeHanlder"
              @handleCurrentChange="productIndexChangeHanlder"></pagination-custom>
          </el-col>
        </el-row>
      </div>
      <div id="map-container" :style="`height:${view.height}px`"></div>
      <div id="mouse-position" class="position_coordinate"></div>
      <div style="position: relative">
        <el-card v-show="editBoard" style="max-width: 480px" class="edit-container">
          <div class="tool-body">
            <el-collapse-transition>
              <el-card class="base-layer-card" size="small">
                <template #header>
                  <div class="base-layer-header">
                    <span>底图选择</span>
                    <el-button link class="button" @click=" popoverVisible = false" :icon="Close"></el-button>
                  </div>
                </template>
                <div class="base-layer-container">
                  <el-card :class="`${currentBaseLayer == layer.type ? 'active' : ''}`" v-for="layer in baseLayers"
                    :key="layer.type" :body-style="{ padding: '0px' }" class="img-card"
                    @click="baseImageClickHandler(layer)">
                    <el-image style="width: 74px; height: 54px" :src="layer.img" :fit="'fill'" />
                    <div style="padding: 5px">
                      <span>{{ layer.name }}</span>
                    </div>
                  </el-card>
                </div>
                <template #footer>
                  <!-- <el-row>
                    <el-col style="display: flex; justify-content: space-between">
                      矢量图层
                      <el-switch v-model="resultLayerVisible" @change="switchChangeHandler" />
                    </el-col>
                  </el-row> -->
                </template>
              </el-card>
            </el-collapse-transition>
          </div>
          <div></div>
        </el-card>
      </div>
     <!--  <div>
        <el-card class="step-card">
          <el-steps style="min-width: 760px" :active="currentStep">
            <el-step @click="changeLayer('step1', '1')" title="原始影像" :icon="PictureFilled" />
            <el-step @click="changeLayer('step2', '2')" title="修正后影像" :icon="Operation" />
            <el-step @click="changeLayer('step3', '3')" title="MPDI产品" :icon="Postcard" />
            <el-step @click="changeLayer('step4', 4)" title="土壤含水量" :icon="Drizzling" />
            <el-step @click="changeLayer('step5', 5)" title="蒸散发计算" :icon="Picture" />
          </el-steps>
        </el-card>
      </div> -->
    </el-col>
  </el-row>
</template>
<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, watch } from "vue";
import { Close, Edit, Picture, Upload, PictureFilled, Operation, Postcard, Drizzling } from "@element-plus/icons-vue";
import paginationCustom from "@/components/pagination/paginationCustom.vue";
import { Map, View } from "ol";
import { Tile as TileLayer, Image } from "ol/layer";
import { WMTS, TileWMS, OSM, Tile, ImageWMS, TileImage } from "ol/source";
import WMTSTileGrid from "ol/tilegrid/WMTS";
import { get, fromLonLat } from "ol/proj";
import MousePosition from "ol/control/MousePosition";
import { format as formatAxirs } from "ol/coordinate";
import "ol/ol.css"; // 导入 OpenLayers 样式文件
import { ScaleLine, defaults as defaultControls } from "ol/control";
import { getWidth, getTopLeft, boundingExtent } from "ol/extent";
import HttpService from "@/api/api";
import baseImg1 from "@/assets/img/vec.jpg";
import baseImg2 from "@/assets/img/img.jpg";
import baseImg3 from "@/assets/img/ter.jpg";
import utils from '@/utils/util'

let map;
const resolutions = [];
const projection = get("EPSG:4326");
const projectionExtent = projection.getExtent();
const size = getWidth(projectionExtent) / 256;
const formLabelAlign = reactive({
  name: "",
  region: "",
  type: "",
});
const tableRef = ref(null)
const currentStep = ref(1)
for (let z = 2; z < 19; ++z) {
  resolutions[z] = size / Math.pow(2, z);
}
const geoserverBaseURL = "http://localhost:8055";
const resultLayerVisible = ref(true);
const editBoard = ref(true);


const currentBaseLayer = ref("imgLayer");
const baseLayers = [
  {
    type: "vecLayer",
    name: "矢量底图",
    img: baseImg1,
  },
  {
    type: "imgLayer",
    name: "影像底图",
    img: baseImg2,
  },
  {
    type: "terLayer",
    name: "地形晕渲",
    img: baseImg3,
  },
];
const popoverVisible = ref(false);
const tableData = ref([])
const satType = ref("");
const imageName = ref('')
const startTime = ref(['2001-1-1', new Date().getTime()]);

const options = [
  {
    value: "GF6_WFV",
    label: "GF6_WFV",
  },
  {
    value: "S2X_MSI",
    label: "S2X_MSI",
  },
];

const initMap = function () {
  const TIANDI_KEY = "eec7fae87888db2dc4c30c0c458fb66b";
  const matrixSet = "c";
  const wmsLayers = new Image({
    source: new ImageWMS({
      url: geoserverBaseURL + "/geoserver/result/wms", // GeoServer的WMS服务URL
      params: {
        LAYERS: "result:" + currentTypeLayer.value, // 要显示的图层的工作空间和名称,'FORMAT': 'image/png', // 图片格式
        VERSION: "1.1.0",
        FORMAT: "image/png", // 图像格式为 PNG
      },
      serverType: "geoserver",
    }),
  });
  wmsLayers.set("name", "baseLayer");
  wmsLayers.setOpacity(1);

  const terLayer = new TileLayer({
    source: new WMTS({
      url: `http://t{0-6}.tianditu.com/${"ter"}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
      layer: "ter",
      matrixSet: matrixSet,
      style: "default",
      crossOrigin: "anonymous", // 解决跨域问题 如无该需求可不添加
      format: "tiles",
      wrapX: true,
      tileGrid: new WMTSTileGrid({
        origin: getTopLeft(projectionExtent),
        //resolutions: res.slice(0, 15),
        resolutions: resolutions,
        matrixIds: [
          "0",
          "1",
          "2",
          "3",
          "4",
          "5",
          "6",
          "7",
          "8",
          "9",
          "10",
          "11",
          "12",
          "13",
          "14",
        ],
      }),
    }),
  });
  terLayer.set("name", "terLayer");

  const imgLayer = new TileLayer({
    source: new WMTS({
      url: `http://t{0-6}.tianditu.com/${"img"}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
      layer: "img",
      matrixSet: matrixSet,
      style: "default",
      crossOrigin: "anonymous", // 解决跨域问题 如无该需求可不添加
      format: "tiles",
      wrapX: true,
      tileGrid: new WMTSTileGrid({
        origin: getTopLeft(projectionExtent),
        //resolutions: res.slice(0, 15),
        resolutions: resolutions,
        matrixIds: [
          "0",
          "1",
          "2",
          "3",
          "4",
          "5",
          "6",
          "7",
          "8",
          "9",
          "10",
          "11",
          "12",
          "13",
          "14",
        ],
      }),
    }),
  });
  imgLayer.set("name", "imgLayer");

  const vecLayer = new TileLayer({
    source: new WMTS({
      url: `http://t{0-6}.tianditu.com/${"vec"}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
      layer: "vec",
      matrixSet: matrixSet,
      style: "default",
      crossOrigin: "anonymous", // 解决跨域问题 如无该需求可不添加
      format: "tiles",
      wrapX: true,
      tileGrid: new WMTSTileGrid({
        origin: getTopLeft(projectionExtent),
        //resolutions: res.slice(0, 15),
        resolutions: resolutions,
        matrixIds: [
          "0",
          "1",
          "2",
          "3",
          "4",
          "5",
          "6",
          "7",
          "8",
          "9",
          "10",
          "11",
          "12",
          "13",
          "14",
        ],
      }),
    }),
  });

  vecLayer.set("name", "vecLayer");

  const cvaLayer = new TileLayer({
    source: new WMTS({
      url: `http://t{0-6}.tianditu.com/${"cva"}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
      layer: "cva",
      matrixSet: matrixSet,
      style: "default",
      crossOrigin: "anonymous", // 解决跨域问题 如无该需求可不添加
      format: "tiles",
      wrapX: true,
      tileGrid: new WMTSTileGrid({
        origin: getTopLeft(projectionExtent),
        resolutions: resolutions,
        matrixIds: [
          "0",
          "1",
          "2",
          "3",
          "4",
          "5",
          "6",
          "7",
          "8",
          "9",
          "10",
          "11",
          "12",
          "13",
          "14",
        ],
      }),
    }),
  });
  cvaLayer.set("name", "cvaLayer");

  map = new Map({
    target: "map-container",
    layers: [
      // 底图
      terLayer,
      vecLayer,
      imgLayer,
      wmsLayers,
      cvaLayer,
    ],
    view: new View({
      projection: projection,
    }),
    controls: defaultControls({
      attribution: true,
      zoom: false,
      rotate: true,
    }).extend([]),
  });

  // 创建一个包含四个角点的Extent对象

  map.getView().fit(JSON.parse(currentProduct.value['box']), {
    constrainResolution: false, // 可选，设置是否约束地图视图的分辨率
  });

  var mousePositionControl = new MousePosition({
    coordinateFormat: function (coordinate) {
      return formatAxirs(coordinate, "经度:{x} 纬度:{y}", 2);
    },
    projection: "EPSG:4326",
    className: "custom-mouse-position",
    target: document.getElementById("mouse-position"), //将位置数据放到那里
  });
  map.addControl(mousePositionControl);

  // 比例尺控件
  let scaleLine = new ScaleLine({
    units: "metric",
  });
  map.addControl(scaleLine);
};

const baseImageClickHandler = function (layer) {
  switchBaseLayer(layer.type);
  currentBaseLayer.value = layer.type;
};
const switchBaseLayer = (layerType) => {
  if (!map) return;
  map.getLayers().forEach((layer) => {
    if (
      layer.values_.name == layerType ||
      layer.values_.name == "resultLayer" ||
      layer.values_.name == "baseLayer" ||
      layer.values_.name == "cvaLayer"
    ) {
      layer.setVisible(true);
      if (!resultLayerVisible.value && layer.values_.name == "resultLayer") {
        layer.setVisible(false);
      }
    } else {
      layer.setVisible(false);
    }
  });
};


const viewRecordHandler = function (row) {
  if (row && map) {
    currentProduct.value = row
    console.log(currentProduct.value)
    var newLayer = new TileLayer({ // 新的 WMS 图层 
      source: new TileWMS({
        url: geoserverBaseURL + '/geoserver/result/wms', // GeoServer的WMS服务URL
        params: {
          'LAYERS': 'result:' + currentProduct.value[`step${currentStep.value}`],
          'VERSION': '1.1.0',
          'FORMAT': 'image/png', // 图像格式为 PNG
        },
        serverType: 'geoserver'
      })
    });
    newLayer.set('name', "baseLayer")
    map.getLayers().setAt(3, newLayer); // 替换第二个图层（索引为 1）
    map.getView().fit(JSON.parse(currentProduct.value['box']), {
      constrainResolution: false, // 可选，设置是否约束地图视图的分辨率
    });
  }
}

const pagination = reactive({
  page_index: 1,
  page_size: 15,
  page_total: 0,
});
const productLoading = ref(false)
let currentTypeLayer = ref('GF1_WFV0829_origin_1')
const currentProduct = ref(null)
const getPorducts = function () {
  productLoading.value = true
  setTimeout(() => {
    let params = {
      page_index: pagination.page_index,
      page_size: pagination.page_size,
      keyword: imageName
    };
    tableData.value.length = 0
    HttpService.module1Manage.getPorducts(
      params,
      (res) => {
        if (res.status == 200) {
          res.data.data.forEach((product) => {
            tableData.value.push(product)
          })
          tableRef.value.setCurrentRow(tableData.value[0])
          currentTypeLayer.value = tableData.value[0].step1
          currentProduct.value = tableData.value[0]
          pagination.page_total = res.data.total;
          initMap();
        }
        productLoading.value = false
      },
      (error) => {
        productLoading.value = false
        console.log(error);
      }
    );
  }, 500)
}


const productSizeChangeHanlder = function (page_size: number) {
  pagination.page_size = page_size;
  getPorducts();
};
const productIndexChangeHanlder = function (page_index: number) {
  pagination.page_index = page_index;
  getPorducts();
};
const changeLayer = function (step, current) {
  currentTypeLayer.value = currentProduct.value[step];
  currentStep.value = current;
  var newLayer = new TileLayer({ // 新的 WMS 图层 
    source: new TileWMS({
      url: geoserverBaseURL + '/geoserver/result/wms', // GeoServer的WMS服务URL
      params: {
        'LAYERS': 'result:' + currentTypeLayer.value,
        'VERSION': '1.1.0',
        'FORMAT': 'image/png', // 图像格式为 PNG
      },
      serverType: 'geoserver'
    })
  });
  newLayer.set('name', "baseLayer")
  map.getLayers().setAt(3, newLayer); // 替换第二个图层（索引为 1）
}



getPorducts()

onMounted(() => {

});

var view = reactive({
  height: window.innerHeight,
});

</script>
<style lang="scss" scoped>
.paltform-container {
  position: relative;
}

.header {
  background: url("@/assets/bigScreen/img/title_back.png") no-repeat center;
  background-size: 100% 100%;
  width: 100%;
  height: 114px;
  display: flex;
  position: relative;
  justify-content: space-between;
  background-position: 0px -13px;
  z-index: 200;

  .tit-warp {
    position: relative;
    top: 12px;
    width: 100%;
    display: flex;
    justify-content: center;

    .tit-name {
      font-size: 28px;
      color: #d1e5ff;
      line-height: 30px;
      text-shadow: 1px 2px 0px rgba(95, 129, 151, 0.47),
        2px 4px 2px rgba(58, 99, 137, 0.15), 4px 10px 18px rgba(27, 41, 60, 0.5);
      background: linear-gradient(0deg, #ffffff 0%);
      -webkit-text-stroke: 1px #eff5ff;
      -webkit-text-fill-color: transparent;
    }
  }
}

.tab-container {
  width: 100%;
  position: absolute;
  display: flex;
  top: 20px;
  z-index: 210;

  .tab-box {
    .custom-button {
      flex: 1;
      text-align: center;
      display: inline-block;
      width: 203px;
      height: 88px;
      line-height: 70px;
      font-weight: bold;
      font-size: 16px;
      text-shadow: 8px 11px 1px rgba(145, 199, 255, 0.05),
        18px 38px 32px rgba(0, 0, 0, 0.24);
      font-style: italic;
      background: url("@/assets/bigScreen/img/tab_button.png") no-repeat;
      color: #c1f5ff;
      background-position: 0px -10px;
      cursor: pointer;

      &:hover {
        background: url("@/assets/bigScreen/img/tab_button_active.png") no-repeat;
        background-position: 0px -10px;
      }
    }

    .active {
      background: url("@/assets/bigScreen/img/tab_button_active.png") no-repeat;
      background-position: 0px -10px;
    }
  }

  .left-box {
    flex: 0.35;
    display: flex;
  }

  .middle-box {
    flex: 0.3;
  }

  .right-box {
    flex: 0.35;
    display: flex;
  }
}

#map-container {
  width: 100%;
  height: 600px;
  cursor: pointer;
  position: absolute;
  top: 0;
  z-index: 10;
}

.position_coordinate {
  color: #fff;
  position: absolute;
  font-size: 14px;
  bottom: 20px;
  right: 20px;
  z-index: 999;
  text-align: center;
  line-height: 30px;
  background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));
  padding: 5px 10px;
  z-index: 110;
}

.base-layer-card {
  background: none;

  .base-layer-header {
    display: flex;
    justify-content: space-between;
  }

  .base-layer-container {
    display: flex;
    justify-content: space-between;

    .active {
      border: 2px solid #56a3f0;
    }
  }

  .img-card {
    border: 2px solid hsla(210, 96%, 54%, 0);
    cursor: pointer;

    &:hover {
      border: 2px solid #4685c4;
    }
  }
}

.task-card {
  z-index: 100;
  position: absolute;
  height: 680px;
  background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));
  box-shadow: 0px 10px 19px 1px rgba(92, 99, 106, 0.38);
  border-radius: 3px;
  left: 34px;
  top: 120px;
  padding: 10px;

  .detial-con {
    padding: 10px;
    box-sizing: border-box;

    li {
      margin-bottom: 5px;
    }
  }

  overflow: scroll;
  overflow-x: hidden;
}
</style>
<style lang="scss">
.base-layer-card {
  .el-card__header {
    padding: 5px !important;
  }

  .el-card__body {
    padding: 15px;
  }

  .el-card__footer {
    padding: 5px !important;
  }
}

.edit-container {
  z-index: 100;
  position: absolute;
  background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));
  box-shadow: 0px 10px 19px 1px rgba(92, 99, 106, 0.38);
  border-radius: 3px;
  right: 34px;
  top: 50px;
  width: 300px;

  .tool-header {
    padding: 0 5px 5px;
    border-bottom: 1px solid rgb(109, 194, 236);
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .tool-body {
    .el-avatar {
      margin-right: 10px;
    }
  }

  .tool-footer {
    padding: 10px 5px;
    border-top: 1px solid rgb(109, 194, 236);
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .el-card__body {
    padding: 5px;

    .el-input__wrapper {
      color: #d1e5ff;
    }
  }

  .tool-body {
    &>.el-card {
      border: none !important;

      .el-card.is-always-shadow {
        box-shadow: none !important;
      }
    }

    .base-layer-card.is-always-shadow {
      box-shadow: none !important;
    }
  }
}

.task-card {
  .el-form-item {
    margin-bottom: 5px !important;
  }

  .el-select__wrapper {
    box-shadow: 0 0 0 1px rgb(109, 194, 236) inset;
  }

  .filter-container {
    .el-input__wrapper {
      box-shadow: 0 0 0 1px rgb(109, 194, 236) inset;
      background: rgba(34, 42, 51, 0.5);
      color: #d1e5ff;
    }
  }

  .el-table {
    --el-table-header-bg-color: #1b384d9c !important;
    --el-table-tr-bg-color: #2a57779c !important;
    --el-table-border-color: rgb(109, 194, 236);
    --el-table-row-hover-bg-color: #152b3a9c !important;

    tr {
      cursor: pointer;
      color: #ccc;
      background: none;
    }

    .el-table__body tr.current-row> {
      td.el-table__cell {
        // transition: all 1s;
        background-color: #0c1b2975;
        // background-color: #03253dda!important;
        color: rgb(109, 194, 236);
        color: #fff;
      }
    }
  }

  .page-container {
    --el-input-border-color: rgb(109, 194, 236) !important;

    .el-input__wrapper {
      box-shadow: 0 0 0 1px rgb(109, 194, 236) inset;
    }

    .el-select {
      --el-select-border-color-hover: rgb(109, 194, 236) !important;
    }
  }
}

.step-card {
  position: absolute;
  z-index: 200;
  width: 800px;
  bottom: 0;
  left: calc((100% - 800px)/2);
  // background: rgba(21, 30, 40);
  background: linear-gradient(0deg, #0b283b, #0b283b, #0b283b);
  box-shadow: 0px 10px 19px 1px rgba(92, 99, 106, 0.38);
  border-radius: 3px;

  .el-card__body {
    padding: 15px;
    display: flex;
    justify-content: center;
  }

  .el-step__icon {
    cursor: pointer;
    background: #0b283b;
  }

  .el-step__title {
    cursor: pointer;
  }
}
</style>
